<template>
  <div class="comment-section">
    <!-- 评论输入框 -->
    <div class="comment-input">
      <el-input
        type="textarea"
        :rows="3"
        placeholder="写下你的评论..."
        v-model="newComment"
      >
      </el-input>
      <div class="comment-button">
        <el-button type="primary" :loading="commentLoading" @click="submitComment">发表评论</el-button>
      </div>
    </div>

    <!-- 评论列表 -->
    <div class="comment-list">
      <div v-for="comment in comments" :key="comment.id" class="comment-item">
        <div class="comment-header">
          <el-avatar :size="40" :src="comment.userAvatar"></el-avatar>
          <div class="comment-info">
            <div class="username">{{ comment.username }}</div>
            <div class="time">{{ formatTime(comment.createdAt) }}</div>
          </div>
        </div>
        <div class="comment-content">{{ comment.content }}</div>
        <div class="comment-actions">
          <span class="action" @click="likeComment(comment)">
            <i :class="[comment.isLiked ? 'el-icon-star-on' : 'el-icon-star-off', {'liked': comment.isLiked}]"></i>
            {{ comment.likesCount }}
          </span>
          <span class="action" @click="showReplyInput(comment)">
            <i class="el-icon-chat-dot-round"></i> 回复
          </span>
        </div>
        
        <!-- 回复列表 -->
        <div class="replies-section" v-if="comment.replies && comment.replies.length > 0">
          <!-- 显示前3条回复 -->
          <div class="reply-item" v-for="(reply, index) in showingReplies(comment)" :key="reply.id">
            <div class="reply-header">
              <el-avatar :size="30" :src="reply.userAvatar"></el-avatar>
              <div class="reply-info">
                <span class="username">{{ reply.username }}</span>
                <span class="reply-to" v-if="reply.replyToUsername">回复 {{ reply.replyToUsername }}</span>
                <div class="time">{{ formatTime(reply.createdAt) }}</div>
              </div>
            </div>
            <div class="reply-content">{{ reply.content }}</div>
            <div class="reply-actions">
              <span class="action" @click="showReplyToReply(comment, reply)">
                <i class="el-icon-chat-dot-round"></i> 回复
              </span>
            </div>
          </div>
          
          <!-- 展开/收起回复按钮 -->
          <div class="expand-replies" @click="toggleReplies(comment)">
            <template v-if="hasMoreReplies(comment)">
              展开更多{{ comment.replies.length - initialReplyCount }}条回复
            </template>
            <template v-else-if="comment.isExpanded">
              收起回复
            </template>
          </div>
        </div>

        <!-- 回复输入框 -->
        <div class="reply-input" v-if="comment.showReplyInput">
          <el-input
            type="textarea"
            :rows="2"
            :placeholder="comment.replyToUsername ? `回复 ${comment.replyToUsername}` : '回复评论...'"
            v-model="comment.replyContent"
          >
          </el-input>
          <div class="reply-button">
            <el-button size="small" :loading="replyLoading[comment.id]" @click="submitReply(comment)">回复</el-button>
            <el-button size="small" v-if="comment.replyToUsername" @click="cancelReplyTo(comment)">取消回复</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { createComment, createReply, toggleCommentLike } from '@/api/api';
import { getUserAvatar, getUsername } from '@/api/auth';

export default {
  name: 'Comment',
  props: {
    activityId: {
      type: [String, Number],
      required: true
    },
    comments: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      newComment: '',
      currentUser: {
        username: getUsername(),
        userAvatar: this.checkAvatarUrl(getUserAvatar()) || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
      },
      replyLoading: {},
      commentLoading: false,
      initialReplyCount: 3
    }
  },
  methods: {
    checkAvatarUrl(url) {
      if (!url) return url;
      return url.replace(/^https:/, 'http:');
    },
    formatTime(timestamp) {
      if (!timestamp) return '';
      
      const now = new Date();
      const date = new Date(timestamp);
      const diff = now - date;
      
      // 计算时间差
      const minutes = Math.floor(diff / 1000 / 60);
      const hours = Math.floor(minutes / 60);
      const days = Math.floor(hours / 24);
      
      // 如果小于1分钟
      if (minutes < 1) {
        return '刚刚';
      }
      // 如果小于1小时
      if (minutes < 60) {
        return `${minutes}分钟前`;
      }
      // 如果小于24小时
      if (hours < 24) {
        return `${hours}小时前`;
      }
      // 如果小于7天
      if (days < 7) {
        return `${days}天前`;
      }
      
      // 如果是今年
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hour = date.getHours().toString().padStart(2, '0');
      const minute = date.getMinutes().toString().padStart(2, '0');
      
      if (year === now.getFullYear()) {
        return `${month}月${day}日 ${hour}:${minute}`;
      }
      
      // 如果是往年
      return `${year}年${month}月${day}日 ${hour}:${minute}`;
    },
    async submitComment() {
      if (!this.newComment.trim()) {
        this.$message.warning('请输入评论内容')
        return
      }

      console.log('当前活动ID:', this.activityId);
      
      if (!this.activityId) {
        this.$message.error('活动ID不能为空')
        return
      }

      this.commentLoading = true

      try {
        const response = await createComment({
          activity_id: Number(this.activityId),
          content: this.newComment
        });

        console.log('创建评论成功', response)

        // 构造新评论对象
        const newComment = response

        // 更新评论列表
        this.$emit('update:comments', [ newComment, ...this.comments])
        this.newComment = ''
        this.$message.success('评论发布成功')
      } catch (error) {
        this.$message.error(error.response?.data?.message || '评论发布失败')
      } finally {
        this.commentLoading = false
      }
    },
    async likeComment(comment) {
      try {
        const response = await toggleCommentLike(comment.id);
        
        // 使用 Vue.set 来确保响应式更新
        this.$set(comment, 'isLiked', response.isLiked);
        this.$set(comment, 'likesCount', response.likes);
        
        this.$message.success(response.isLiked ? '点赞成功' : '取消点赞成功');
      } catch (error) {
        this.$message.error(error.response?.data?.message || '点赞操作失败');
      }
    },
    showReplyInput(comment) {
      this.$set(comment, 'showReplyInput', !comment.showReplyInput)
      this.$set(comment, 'replyContent', '')
      this.$set(comment, 'replyToUsername', '')
    },
    showReplyToReply(comment, reply) {
      this.$set(comment, 'showReplyInput', true)
      this.$set(comment, 'replyContent', '')
      this.$set(comment, 'replyToUsername', reply.username)
    },
    cancelReplyTo(comment) {
      this.$set(comment, 'replyToUsername', '')
    },
    async submitReply(comment) {
      if (!comment.replyContent.trim()) {
        this.$message.warning('请输入回复内容')
        return
      }

      // 设置加载状态
      this.$set(this.replyLoading, comment.id, true)

      try {
        const requestData = {
          activity_id: Number(this.activityId),
          comment_id: comment.id,
          content: comment.replyContent,
          reply_to_username: comment.replyToUsername || null,
        }

        console.log('回复请求数据', requestData)
        const response = await createReply(requestData);
        console.log('回复请求响应', response)
        // 构造回复对象
        const reply = {
          id: response.id,
          userAvatar: response.userAvatar || this.currentUser.userAvatar,
          username: response.username || this.currentUser.username,
          content: response.content,
          createTime: response.createTime,
          replyToUsername: response.replyToUsername
        }

        if (!comment.replies) {
          this.$set(comment, 'replies', [])
        }
        comment.replies.push(reply)
        
        comment.showReplyInput = false
        comment.replyContent = ''
        comment.replyToUsername = ''
        
        this.$message.success('回复发布成功')
      } catch (error) {
        this.$message.error(error.response?.data?.message || '回复发布失败')
      } finally {
        // 无论成功还是失败，都要取消加载状态
        this.$set(this.replyLoading, comment.id, false)
      }
    },
    showingReplies(comment) {
      if (!comment.replies) return [];
      return comment.replies.slice(0, comment.isExpanded ? comment.replies.length : this.initialReplyCount);
    },
    
    hasMoreReplies(comment) {
      return comment.replies && 
             comment.replies.length > this.initialReplyCount && 
             !comment.isExpanded;
    },
    
    toggleReplies(comment) {
      this.$set(comment, 'isExpanded', !comment.isExpanded);
    }
  },
  watch: {
    comments: {
      handler(newVal) {
        // 检查并更新所有评论的头像URL
        newVal.forEach(comment => {
          comment.userAvatar = this.checkAvatarUrl(comment.userAvatar);
          if (comment.replies) {
            comment.replies.forEach(reply => {
              reply.userAvatar = this.checkAvatarUrl(reply.userAvatar);
            });
          }
        });
        console.log('更新评论列表:', newVal)
      },
      deep: true
    }
  },
  created() {
    // 初始化时检查并更新所有评论的头像URL
    if (this.comments) {
      this.comments.forEach(comment => {
        comment.userAvatar = this.checkAvatarUrl(comment.userAvatar);
        if (comment.replies) {
          comment.replies.forEach(reply => {
            reply.userAvatar = this.checkAvatarUrl(reply.userAvatar);
          });
        }
      });
    }
  }
}
</script>

<style scoped>
.comment-section {
  margin-top: 20px;
}

.comment-input {
  margin-bottom: 20px;
}

.comment-button {
  margin-top: 10px;
  text-align: right;
}

.comment-list {
  margin-top: 20px;
}

.comment-item {
  padding: 15px;
  border-bottom: 1px solid #eee;
  font-family: "Cera-Bold", sans-serif;
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.comment-info {
  margin-left: 10px;
}

.username {
  font-weight: bold;
  font-size: 14px;
}

.time {
  color: #999;
  font-size: 12px;
}

.comment-content {
  margin: 10px 0;
  font-size: 14px;
}

.comment-actions {
  margin-top: 10px;
}

.action {
  margin-right: 20px;
  color: #666;
  cursor: pointer;
  font-size: 13px;
}

.action:hover {
  color: #409EFF;
}

.liked {
  color: #FFBD00;
}

.replies-section {
  margin-left: 50px;
  margin-top: 10px;
}

.reply-item {
  padding: 10px 0;
}

.reply-header {
  display: flex;
  align-items: center;
}

.reply-info {
  margin-left: 10px;
}

.reply-to {
  color: #409EFF;
  margin-left: 5px;
}

.reply-input {
  margin-top: 10px;
  margin-left: 50px;
}

.reply-button {
  margin-top: 5px;
  text-align: right;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.reply-actions {
  margin-top: 5px;
}

.reply-actions .action {
  font-size: 12px;
  color: #666;
}

.expand-replies {
  margin-top: 10px;
  text-align: right;
  color: #409EFF;
  cursor: pointer;
}

.replies-section {
  margin-left: 40px;
  margin-top: 10px;
}

.reply-item {
  margin-bottom: 8px;
  padding: 8px;
  background: #f9f9f9;
  border-radius: 4px;
}

.expand-replies {
  color: #409EFF;
  cursor: pointer;
  padding: 8px 0;
  font-size: 14px;
}

.expand-replies:hover {
  opacity: 0.8;
}
</style>